package com.cskaoyan.user.controller;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.api.UserLoginResponseApi;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dto.TokenDto;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.ILoginService;
import com.cskaoyan.user.service.IUserRegisterService;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @auther 10-何兴绕
 * @Date 2022年10月25日 18:17
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    ILoginService loginService;

    @Autowired
    UserConverterMapper converterMapper;

    @Autowired
    IKaptchaService kaptchaService;

    @Autowired
    IUserRegisterService iUserRegisterService;

    @Autowired
    RedissonClient redissonClient;

    /**
     * 登录
     *
     * @param userLoginRequest
     * @param response
     * @return
     */
    @PostMapping("login")
    public ResponseData login(@RequestBody UserLoginRequest userLoginRequest,
                              HttpServletResponse response,
                              HttpServletRequest request) {

        UserLoginResponse login = loginService.login(userLoginRequest);

        UserLoginResponseApi responseApi = converterMapper.converterApi(login);

        if (login == null) {
            return new ResponseUtil().setErrorMsg("用户名或密码不正确");
        }

        KaptchaCodeRequest codeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        codeRequest.setCode(userLoginRequest.getCaptcha());
        codeRequest.setUuid(uuid);
        kaptchaService.validateKaptchaCode(codeRequest);

        if ("N".equals(login.getToken())) {
            return new ResponseUtil().setErrorMsg("用户名尚未激活");
        }

        String jsonString = JSON.toJSONString(responseApi);
        String token = JwtTokenUtils.builder().msg(jsonString).build().creatJwtToken();
        Cookie cookie = new Cookie("access_token", token);
        cookie.setMaxAge(86400);
        cookie.setPath("/");
        CookieUtil.setCookie(response, cookie);

        login.setToken(token);
        return new ResponseUtil().setData(login);
    }

    /**
     * 验证用户登录
     *
     * @param request
     * @return
     */
    @GetMapping("login")
    public ResponseData verifyLogin(HttpServletRequest request) {

        String access_token = CookieUtil.getCookieValue(request, "access_token");

        if (access_token == null) {
            return new ResponseUtil<>().setErrorMsg("token校验失败");
        }

        String jwt = JwtTokenUtils.builder().token(access_token).build().freeJwt();

        UserLoginResponseApi loginResponseApi = JSON.parseObject(jwt, UserLoginResponseApi.class);

        TokenDto tokenDto = new TokenDto();
        tokenDto.setUid(loginResponseApi.getUid());
        tokenDto.setUsername(loginResponseApi.getUsername());
        tokenDto.setFile(loginResponseApi.getFile());

        return new ResponseUtil<>().setData(tokenDto);
    }

    /**
     * 用户退出
     *
     * @Author 12-江涛
     * @Date 2022/10/25 21:04
     */
    @GetMapping("/loginOut")
    public ResponseData loginOut(HttpServletRequest request, HttpServletResponse response) {

        Cookie[] cookies = request.getCookies();
//        for (Cookie cookie : cookies) {
//            cookie.setMaxAge(0);
//            response.addCookie(cookie);
//        }

        if (cookies != null) {

            for (Cookie cookie : cookies) {
                if ("access_token".equals(cookie.getName())) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }

        return new ResponseUtil<>().setData(null);
    }

    /**
     * 用户注册激活
     *
     * @Author 12-江涛
     * @Date 2022/10/25 21:04
     */
    @GetMapping("/verify")
    public ResponseData verify(String uid, String username) {

        UserVerifyRequest userVerifyRequest = new UserVerifyRequest();
        userVerifyRequest.setUsername(username);
        userVerifyRequest.setUuid(uid);
        iUserRegisterService.verify(userVerifyRequest);

        return new ResponseUtil<>().setData(null);
    }

    @Autowired
    IUserRegisterService registerService;

    /**
     * 用户注册
     *
     * @param registerRequest：接收参数
     * @param request：请求信息
     * @return ：注册信息
     */
    @PostMapping("/register")
    public ResponseData register(@RequestBody UserRegisterRequest registerRequest, HttpServletRequest request) {
        // 校验验证码
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(registerRequest.getCaptcha());
        // 没有抛出异常表示验证成功
        kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        // 向用户表中插入数据
        UserRegisterResponse response = registerService.register(registerRequest);
        // 插入失败
        if (!response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        // 插入成功
        return new ResponseUtil<>().setData(null);
    }

}
